#!/usr/bin/perl -I../lib -I../../../lib -w

use strict;
use POSIX qw{EWOULDBLOCK mkfifo};

use IO::Prompt;
use Time::HiRes qw{usleep};
use Named::Pipes;




$SIG{PIPE} = sub {
   warn "received SIGPIPE. Exiting!\n";
   exit(1);
};

my ($fout,$fin,$err) = Named::Pipes->open('toap','tome','err','bc');

$fin->blocking(0);

my $result;
while (prompt("Expression (CTRL-D to end): ", '-l')) {

   print "Sending expression to external 'bc' process ...\n";
   syswrite $fout, $_;
   usleep(10);
   my $bytes = sysread $fin, $result, 1024;
   if (defined($bytes))  {
      if ($bytes) {
         print "Obtained result from external 'bc' process:\n\t$result";
      }
      else { # EOF
         warn "bc process broken!\n";
         last;
      }
   }
   else {
      print "Nothing has arrived (yet) ...\n";
   }
}
